package com.tengits.upgrade;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

public class WaterMarkUtils {
    public static void addWatermarkView(Activity activity, ViewGroup rootView) {
        View framView = LayoutInflater.from(activity).inflate(R.layout.layout_watermark, null);
        framView.setId(R.id.watermarklayoutadd);
        //可对水印布局进行初始化操作
        View lastView = rootView.findViewById(R.id.watermarklayoutadd);
        if(lastView != null) {
            rootView.removeView(lastView);
        }
        rootView.addView(framView);
    }

    public static void removeWatermarkView(ViewGroup rootView) {
        View lastView = rootView.findViewById(R.id.watermarklayoutadd);
        if(lastView != null) {
            rootView.removeView(lastView);
        }
    }

    public static void showWatermarkView(Activity activity, String string) {
        ViewGroup rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content);
        if(TextUtils.isEmpty(string)) {
            removeWatermarkView(rootView);
            return;
        }
        addWatermarkView(activity, rootView);
        View framView = rootView.findViewById(R.id.watermarklayoutadd);
        WindowManager wm = (WindowManager)activity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        ((ImageView)framView.findViewById(R.id.ivWm)).setImageDrawable(getMarkTextBitmapDrawable(activity, string, width, height));
    }
    /**
     * 获得文字水印的图片
     * @param width
     * @param height
     * @return
     */
    public static Drawable getMarkTextBitmapDrawable(Context gContext, String gText, Integer width, Integer height) {
        Bitmap bitmap = getMarkTextBitmap(gContext, gText, width, height);
        if (bitmap != null) {
            BitmapDrawable drawable = new BitmapDrawable(gContext.getResources(), bitmap);
            drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
            drawable.setDither(true);
            return drawable;
        }
        return null;
    }

    public static Bitmap getMarkTextBitmap(Context gContext, String gText, Integer width, Integer height) {
        Float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 18f, gContext.getResources().getDisplayMetrics());
        Float inter = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120f, gContext.getResources().getDisplayMetrics());

        Integer sideLength = 0;
        if (width > height) {
            sideLength = (int)Math.sqrt((2 * (width * width)));
        } else {
            sideLength = (int)Math.sqrt((2 * (height * height)));
        }

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Rect rect = new Rect();
        paint.setTextSize(textSize);
        //获取文字长度和宽度
        paint.getTextBounds(gText, 0, gText.length(), rect);

        int strwid = rect.width();
        int strhei = rect.height();

        Bitmap markBitmap = null;
        try {
            markBitmap = Bitmap.createBitmap(sideLength, sideLength, Bitmap.Config.ARGB_4444);
            Canvas canvas = new Canvas(markBitmap);
            //创建透明画布
            canvas.drawColor(Color.TRANSPARENT);

            paint.setColor(Color.BLACK);
            paint.setAlpha((int)(0.1 * 255f));
            // 获取跟清晰的图像采样
            paint.setDither(true);
            paint.setFilterBitmap(true);

            //先平移，再旋转才不会有空白，使整个图片充满
            if (width > height) {
                canvas.translate(width * 1.0f - sideLength * 1.0f - inter, sideLength - width + inter);
            } else {
                canvas.translate(height * 1.0f - sideLength * 1.0f - inter, sideLength - height + inter);
            }

            //将该文字图片逆时针方向倾斜45度
            canvas.rotate((-45)*1.0f);

            int i = 0;
            while (i <= sideLength) {
                int count = 0;
                int j = 0;
                while (j <= sideLength) {
                    if (count % 2 == 0) {
                        canvas.drawText(gText, i * 1.0f, j * 1.0f, paint);
                    } else {
                        //偶数行进行错开
                        canvas.drawText(gText, (i + strwid / 2) * 1.0f, j * 1.0f, paint);
                    }
                    j = (int)(j * 1.0f + inter + strhei * 1.0f);
                    count++;
                }
                i = (int)(i * 1.0f + strwid * 1.0f + inter);
            }
            canvas.save();
        } catch (OutOfMemoryError e) {
            if (markBitmap != null && !markBitmap.isRecycled()) {
                markBitmap.recycle();
                markBitmap = null;
            }
        }

        return markBitmap;
    }
}
